'use strict';

const Service = require('egg').Service;

class PosFolderService extends Service {

  // 获取文件夹列表以及文件夹下文件数量
  async select(params) {
    try {
      const query = {
        where: {
          type: params.type
        },
        order: [["sort", "ASC"]],
      }
      const folderRes = await this.ctx.model.PosFolder.findAll(query);
      let counts;
      console.log('params', params.type)
      if (Number(params.type) === 1) {
        counts = await this.ctx.model.PosPhoto.count({
          attributes: ["folderId"],
          group: "folderId",
        })
      }
      if (Number(params.type) === 2) {
        counts = await this.ctx.model.PosVideo.count({
          attributes: ["folderId"],
          group: "folderId",
        })
      }
      const countEnum = {};
      console.log('counts', counts, folderRes)
      counts.map((count) => {
        countEnum[count.folderId] = count.count;
      });
      const folders = this.ctx.helper.deepCopy(folderRes)
      folders.map((folder) => {
        folder.count = countEnum[folder.id] || 0;
        return folder;
      });
      return this.ctx.helper.ormSuccess(folders)
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }

  /**
   * @description 创建文件夹
   * @param {PosFolderDto.createDto} 参数
   */
  async create(params) {
    try {
      await this.ctx.model.PosFolder.create(params);
      return this.ctx.helper.ormSuccess();
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }


  /**
   * @description 编辑
   * @param {*} id id
   * @param {PosFolderDto.editDto} 参数
   * @returns 
   */
  async edit(id, params) {
    try {
      const editEntity = await this.ctx.model.PosFolder.findByPk(id);
      if (!editEntity) throw '文件夹不存在';
      await editEntity.update(params);
      return this.ctx.helper.ormSuccess();
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }

  /**
   * @description 删除（物理删除）
   * @param {*} id 
   * @returns 
   */
  async del(id) {
    try {
      const entity = await this.ctx.model.PosFolder.findByPk(id);
      if (!entity) throw '文件夹不存在';
      if (entity.isSys) throw '默认文件夹，不允许删除'
      await this.ctx.model.PosFolder.destroy({
        where: {
          id
        }
      })
      if (entity.type === 1) {
        await this.ctx.model.PosPhoto.destroy({
          where: {
            folderId: id
          }
        })
      }

      if (entity.type === 2) {
        await this.ctx.model.PosVideo.destroy({
          where: {
            folderId: id
          }
        })
      }
      // TODO 删除oss资源
      return this.ctx.helper.ormSuccess();
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }
}

module.exports = PosFolderService;
